import os
import requests as req
from . import const

def get_all_minecraft_version(version = "v2") -> dict:
    """
    bmclapi : https://bmclapidoc.bangbang93.com/
    """
    if version == "v2":
        URL = "https://bmclapi2.bangbang93.com/mc/game/version_manifest_v2.json"
    else:
        URL = "https://bmclapi2.bangbang93.com/mc/game/version_manifest.json"
    
    version_manifest = req.get(url = URL, headers=const.headers)
    try:
        version_manifest.raise_for_status()
    except req.exceptions.ConnectionError as e:
        raise const.ConnectionError("请求错误: {}".format(e))
    except req.exceptions.RequestException as e:
        raise const.RequestException("请求错误: {}".format(e))
    except Exception as e:
        raise Exception(e)
    
    version_manifest = version_manifest.json()
    
    result = {
        "latest":{
            "release": version_manifest["latest"]["release"],
            "snapshot": version_manifest["latest"]["release"]
        },
        "versions":[]
    }
    
    for item in version_manifest["versions"]:
        result["versions"].append({
            "id":item["id"],
            "type":item["type"],
            "time":item["time"],
            "releaseTime":item["releaseTime"]
        })
    
    return result



def setup_minecraft_server_eula(version_id : str, server_dir : str):
    eula = True
    server_path = os.path.join(server_dir, version_id)
    if not os.path.exists(server_path):
        raise const.ThisServerVersionDoesNotExistError(f"要设置的Minecraft服务器核心不存在于 {server_dir}")
    
    if eula:
        eula_path = os.path.join(server_path,"eula.txt")
        with open(eula_path,"w") as file:
            file.write(const.eula)

            
def read_minecraft_server_properties(version_id : str, server_dir : str):
    server_path = os.path.join(server_dir, version_id)
    rusult = {}
    if not os.path.exists(server_path):
        raise const.ThisServerVersionDoesNotExistError(f"要设置的Minecraft服务器核心不存在于 {server_dir}")
    try:
        with open(os.path.join(server_path, "server.properties"), "r") as file:
            file_contents = file.readlines()
    except FileNotFoundError as e:
        raise const.ThisServerServerPropertiesDoesNotExistError(f"要设置的Minecraft服务器核心不存在于 {server_dir}，或 server.properties 文件不存在")



    for file_content in file_contents:
        temp = str(file_content).split("=")
        try:
            rusult.update({temp[0]:temp[1]})
        except IndexError:
            continue

    return rusult


def write_minecraft_server_properties(version_id : str, server_dir : str, content : dict):
    server_path = os.path.join(server_dir, version_id)
    if not os.path.exists(server_path):
        raise const.ThisServerVersionDoesNotExistError(f"要设置的Minecraft服务器核心不存在于 {server_dir}")
   
    with open(os.path.join(server_path, "server.properties"), "w") as file:
        for item in content.items():
            file.write(f"{item[0]}={item[1]}\n")
    